import React, { useMemo, useRef } from "react";
import useMergedState from "rc-util/lib/hooks/useMergedState";
import { Checkbox, Radio, Select, Space, TimePicker } from "antd";
import { CheckboxGroupWrap, LabelStyle, RadioWrap, TextStyle } from "./styles";
import dayjs from "dayjs";
import {
  arrayToCronString,
  getCronSplitValue,
  getTrueHour,
} from "./utils/help";
import {
  dayPoint,
  hourPoint,
  timeCommonProps,
  weekPoint,
} from "./utils/constants";

export interface CronProps {
  value?: string;
  defaultValue?: string;
  onChange?: any;
}

export const Cron = ({ value = "", defaultValue, onChange }: CronProps) => {
  const [cronValue = "", setCronValue] = useMergedState(defaultValue, {
    defaultValue,
    value,
    onChange: (value) => {
      onChange && onChange(value);
    },
  });

  const lastMultTempRef = useRef(6);

  const cronSplitValue = getCronSplitValue(cronValue || "");

  const option1Value = useMemo(() => {
    if (cronSplitValue[weekPoint] != "?" && cronSplitValue[weekPoint] != "*") {
      return 2;
    }
    if (cronSplitValue[dayPoint] != "?" && cronSplitValue[dayPoint] != "*") {
      return 3;
    }
    return 1;
  }, [cronSplitValue]);

  const option2Value = useMemo(() => {
    const hour = cronSplitValue[hourPoint];
    if (hour.indexOf("/") > -1) {
      return 2;
    }
    return 1;
  }, [cronSplitValue]);

  const everyDayTimePickerValue = useMemo(() => {
    const second = cronSplitValue[0] || 0;
    const minute = cronSplitValue[1] || 0;
    const hour = cronSplitValue[2].split("/")[0] || 0;
    return dayjs()
      .set("hour", Number(hour))
      .set("minute", Number(minute))
      .set("second", Number(second)) as any;
  }, [cronSplitValue]);

  const everyDayMultTimePickerValue = useMemo(() => {
    const second = cronSplitValue[0] || 0;
    const minute = cronSplitValue[1] || 0;
    const hour = cronSplitValue[2].split("/")[0] || 0;
    return dayjs()
      .set("hour", Number(hour))
      .set("minute", Number(minute))
      .set("second", Number(second)) as any;
  }, [cronSplitValue]);

  const everyDayMultValue = useMemo(() => {
    const mult = cronSplitValue[2].split("/")[1] || 6;
    return Number(mult);
  }, [cronSplitValue]);

  const weekValue = (cronSplitValue[weekPoint] || "")
    .split(",")
    .filter((a) => a == "0" || !!a)
    .map((m) => Number(m));

  const dayValue = (cronSplitValue[dayPoint] || "")
    .split(",")
    .filter((a) => a == "0" || !!a)
    .map((m) => Number(m));

  return (
    <div>
      <RadioWrap>
        <Radio.Group
          value={option1Value}
          onChange={(e) => {
            const value = e.target.value;
            // 每天
            if (value == 1) {
              setCronValue(
                arrayToCronString([
                  cronSplitValue[0] || 0,
                  cronSplitValue[1] || 0,
                  cronSplitValue[2] || 0,
                  "*",
                  "*",
                  "?",
                ])
              );
            }
            // 每周
            if (value == 2) {
              setCronValue(
                arrayToCronString([
                  cronSplitValue[0] || 0,
                  cronSplitValue[1] || 0,
                  cronSplitValue[2] || 0,
                  "?",
                  "*",
                  "1",
                ])
              );
            }
            // 每月
            if (value == 3) {
              setCronValue(
                arrayToCronString([
                  cronSplitValue[0] || 0,
                  cronSplitValue[1] || 0,
                  cronSplitValue[2] || 0,
                  "1",
                  "*",
                  "?",
                ])
              );
            }
          }}
          options={[
            {
              label: "每天",
              value: 1,
            },
            {
              label: "每周",
              value: 2,
            },
            {
              label: "每月",
              value: 3,
            },
          ]}
        />
      </RadioWrap>

      <CheckboxGroupWrap
        style={{
          paddingTop: option1Value == 1 ? "0px" : "24px",
        }}
      >
        {option1Value == 1 ? null : option1Value == 2 ? (
          <Checkbox.Group
            value={weekValue}
            onChange={(e) => {
              const inject = e.length ? e : ["0"];
              setCronValue(
                arrayToCronString([
                  cronSplitValue[0],
                  cronSplitValue[1],
                  cronSplitValue[2],
                  "?",
                  cronSplitValue[4],
                  inject.join(","),
                ])
              );
            }}
            options={Array(7)
              .fill(1)
              .map((_, index) => {
                const curIndex = index + 1;
                const label =
                  curIndex == 1
                    ? "星期日"
                    : curIndex == 2
                    ? "星期一"
                    : curIndex == 3
                    ? "星期二"
                    : curIndex == 4
                    ? "星期三"
                    : curIndex == 5
                    ? "星期四"
                    : curIndex == 6
                    ? "星期五"
                    : "星期日";
                return {
                  label: label,
                  value: index + 1,
                };
              })}
          ></Checkbox.Group>
        ) : (
          <Checkbox.Group
            value={dayValue}
            onChange={(e) => {
              const inject = e.length ? e : ["0"];
              setCronValue(
                arrayToCronString([
                  cronSplitValue[0],
                  cronSplitValue[1],
                  cronSplitValue[2],
                  inject.join(","),
                  cronSplitValue[4],
                  "?",
                ])
              );
            }}
            options={Array(31)
              .fill(1)
              .map((_, index) => {
                return {
                  label: index + 1,
                  value: index + 1,
                };
              })}
          ></Checkbox.Group>
        )}
      </CheckboxGroupWrap>
      <RadioWrap
        style={{
          paddingTop: "20px",
          border: "0",
        }}
      >
        <LabelStyle>执行时间</LabelStyle>
        <Radio.Group
          value={option2Value}
          onChange={(e) => {
            if (e.target.value == 1) {
              setCronValue(
                arrayToCronString([
                  getTrueHour(cronSplitValue[0]),
                  getTrueHour(cronSplitValue[1]),

                  getTrueHour(cronSplitValue[2]),
                  cronSplitValue[3],
                  cronSplitValue[4],
                  cronSplitValue[5],
                ])
              );
            } else {
              setCronValue(
                arrayToCronString([
                  getTrueHour(cronSplitValue[0]),
                  getTrueHour(cronSplitValue[1]),
                  getTrueHour(cronSplitValue[2]) +
                    "/" +
                    lastMultTempRef.current,
                  cronSplitValue[3],
                  cronSplitValue[4],
                  cronSplitValue[5],
                ])
              );
            }
          }}
        >
          <Space direction="vertical">
            <Radio value={1}>
              <span
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}
              >
                <div>
                  <TextStyle>每日一次</TextStyle>
                  <TimePicker
                    {...timeCommonProps}
                    minuteStep={60}
                    secondStep={60}
                    hourStep={1}
                    disabled={option2Value != 1}
                    style={{
                      width: "150px",
                    }}
                    value={everyDayTimePickerValue}
                    onChange={(e) => {
                      const second = "0";
                      const minute = "0";
                      const hour = e.get("hour");
                      setCronValue(
                        arrayToCronString([
                          second,
                          minute,
                          hour,
                          cronSplitValue[3],
                          cronSplitValue[4],
                          cronSplitValue[5],
                        ])
                      );
                    }}
                  />
                </div>
              </span>
            </Radio>
            <Radio value={2}>
              <span
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}
              >
                <div>
                  <TextStyle>每日多次，起始时间</TextStyle>
                  <TimePicker
                    {...timeCommonProps}
                    minuteStep={60}
                    secondStep={60}
                    hourStep={1}
                    disabled={option2Value != 2}
                    value={everyDayMultTimePickerValue}
                    onChange={(e) => {
                      const second = "0";
                      const minute = "0";
                      const hour = e.get("hour") || 0;
                      setCronValue(
                        arrayToCronString([
                          second,
                          minute,
                          hour + "/" + lastMultTempRef.current,
                          cronSplitValue[3],
                          cronSplitValue[4],
                          cronSplitValue[5],
                        ])
                      );
                    }}
                  />
                  <TextStyle>每次间隔</TextStyle>
                  <Select
                    disabled={option2Value != 2}
                    value={everyDayMultValue}
                    onChange={(e) => {
                      const hour = cronSplitValue[2];
                      const clearHour = hour.split("/")[0];
                      lastMultTempRef.current = Number(e);
                      setCronValue(
                        arrayToCronString([
                          cronSplitValue[0],
                          cronSplitValue[1],
                          clearHour + "/" + e,
                          cronSplitValue[3],
                          cronSplitValue[4],
                          cronSplitValue[5],
                        ])
                      );
                    }}
                    style={{
                      width: "120px",
                    }}
                    options={[
                      {
                        label: "6小时",
                        value: 6,
                      },
                      {
                        label: "8小时",
                        value: 8,
                      },
                      {
                        label: "12小时",
                        value: 12,
                      },
                    ]}
                  ></Select>
                </div>
              </span>
            </Radio>
          </Space>
        </Radio.Group>
      </RadioWrap>
    </div>
  );
};
